from django.shortcuts import render

from django.shortcuts import HttpResponse
import json
from cmdb import models
from dwebsocket import require_websocket
import time
from cmdb import normal_model

def index(req):
    return HttpResponse('hello world!!! ' + req.GET.get('name', 'not found'))


def welcome(req):
    return render(req, 'welcome.html')


def login(req):
    return render(req, 'login.html')


def logout(req):
    req.session['security'] = None
    return HttpResponse('Logout...')


def login_action(req):
    # 将用户名和密码保存到数据库
    name = req.POST.get('name', 'none')
    pwd = req.POST.get('password', 'none')
    models.TestUser.objects.create(name=name, pwd=pwd)

    req.session['login_status'] = 'ok'

    return HttpResponse('name is ' + req.POST.get('name', 'not found')
                        + '  password is ' + req.POST.get('password', 'not found'))


def users(req):
    # 从数据库读取数据
    user_list = models.TestUser.objects.all()

    return render(req, 'users.html', {'users': user_list})


def test_json(req):
    us = []
    u = normal_model.User()
    u.name = 'name1'
    u.pwd = 'pwd1'
    us.append(u)

    u = normal_model.User()
    u.name = 'zhangshan'
    u.pwd = 'zang'
    us.append(u)

    u = normal_model.User()
    u.name = 'lisi'
    u.pwd = 'si'
    us.append(u)

    return HttpResponse(tojson(us), content_type="application/json")


def tojson(array):
    arr = []
    for a in array:
        arr.append(a.__dict__)
    return json.dumps(arr)


rooms = {}


def send_msg(msg, self):
    global rooms
    mm = json.loads(msg)
    users_websocket = rooms.get(str(mm['room_id']), [])

    for ws in users_websocket:
        # print(ws)
        if ws == self:
            continue

        ws.send(msg)
        # print('sending...')


def setup_room(msg, ws):
    global rooms
    # print(msg)
    mm = json.loads(msg)
    user_id = mm['my_id']
    rid = mm['room_id']
    # 更新到数据库
    rs = models.RoomInfo.objects.filter(room_id=rid, user_id=user_id)
    if not rs:
        models.RoomInfo.objects.create(room_id=rid, user_id=user_id)

    # 保存ws
    room = rooms.get(str(rid), [])
    if len(room) == 0:
        room = [ws]
    else:
        if room.__contains__(ws):
            pass
        else:
            room.append(ws)

    for ws in room:
        if ws.closed:
            room.remove(ws)

    rooms[str(rid)] = room





@require_websocket
def test_websocket(req):

    # mm = req.websocket.wait()
    # req.websocket.send(mm)

    if not req.is_websocket:
        return HttpResponse('http request')

    for mm in req.websocket:
        if mm is None:
            print('break')
            break
        else:
            setup_room(mm, req.websocket)
            send_msg(mm, req.websocket)
            # req.websocket.send(mm)
            print('from client: ' + str(mm))
    #
    # time.sleep(2)
    # req.websocket.send(b'msg from server')
    # print('end... ')

